package com.furongji.education.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.furongji.education.domain.po.Chapter;
import com.furongji.education.domain.po.Section;
import com.furongji.education.domain.vo.ChapterVo;
import com.furongji.education.mapper.ChapterMapper;
import com.furongji.education.service.ChapterService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.furongji.education.service.SectionService;
import lombok.AllArgsConstructor;
import lombok.RequiredArgsConstructor;
import org.springframework.data.web.config.SortHandlerMethodArgumentResolverCustomizer;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程 服务实现类
 * </p>
 *
 * @author furongji
 * @since 2025-05-19
 */
@Service
@RequiredArgsConstructor
public class ChapterServiceImpl extends ServiceImpl<ChapterMapper, Chapter> implements ChapterService {

    private final SectionService sectionService;

    @Override
    public List<ChapterVo> getChapterAndSection(String courseId) {
        List<ChapterVo> chapterVoList = new ArrayList<>();

        // 查询出课程对应的章节
        LambdaQueryWrapper<Chapter> chapterWrapper = new LambdaQueryWrapper<>();
        chapterWrapper.eq(Chapter::getCourseId, courseId);
        List<Chapter> chapterList = super.list(chapterWrapper);

        // 查询出每一章对应的小节
        for (Chapter chapter : chapterList) {
            LambdaQueryWrapper<Section> sectionWrapper = new LambdaQueryWrapper<>();
            sectionWrapper.eq(Section::getChapterId, chapter.getId());
            List<Section> sectionList = sectionService.list(sectionWrapper);
            // 封装到vo对象中并且加入集合
            ChapterVo chapterVo = new ChapterVo(chapter.getId(), chapter.getTitle(), sectionList);
            chapterVoList.add(chapterVo);
        }
        return chapterVoList;
    }

    @Override
    @Transactional
    public Boolean deleteChapter(String id) {
        LambdaQueryWrapper<Section> sectionWrapper = new LambdaQueryWrapper<>();
        sectionWrapper.eq(Section::getChapterId, id);
        List<Section> sectionList = sectionService.list(sectionWrapper);
        boolean chapter = super.removeById(id);
        System.err.println(sectionList);
        if (sectionList.isEmpty()) {
            return chapter;
        } else {
            boolean section = sectionService.remove(sectionWrapper);
            return chapter && section;
        }
    }
}
